package com.example.demo.controller;

import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class StudentController {

    @Autowired
    StudentService studentService;

    @RequestMapping(value = "/selectStudent")
    @ResponseBody
    public ModelAndView selectStudent(int sId){
        ModelAndView m = new ModelAndView("select");
        Student student = studentService.selectStudent(sId);
        m.addObject("sId",student.getsId());
        m.addObject("sName",student.getsName());
        return m;
    }

    @RequestMapping(value = "/selectStudentById")
    @ResponseBody
    public ModelAndView selectStudentById(){
        ModelAndView m = new ModelAndView("list");
        List<Student> list = studentService.selectStudentById();
        for (Student s: list
             ) {
            System.out.println(s);
        }
        m.addObject("List",list);
        return m;
    }

    @RequestMapping("/delectStudent")
    @ResponseBody
    public ModelAndView delectStudent(int sId){
        ModelAndView m = new ModelAndView("delect");
        if (studentService.selectStudent(sId) != null) {
            boolean b = studentService.deleteStduent(sId);
            if (b) {
                m.addObject("message", "删除学号" + sId + "成功");
            } else
                m.addObject("message", "删除学号" + sId + "失败");
        }else
            m.addObject("message", "学号" + sId + "不存在");
        return m;
    }

    @RequestMapping("/updateStudent")
    @ResponseBody
    public ModelAndView updateStudent(int sId,String sName){
        ModelAndView m = new ModelAndView("delect");
        if (studentService.selectStudent(sId) != null){

            boolean b = studentService.updateStudent(sId,sName);
            if (b) {
                m.addObject("message", "更新信息" + sId + "成功");
            } else
                m.addObject("message", "更新学号" + sId + "失败");
        }else
            m.addObject("message", "学号" + sId + "不存在");
        return m;
        }

    @RequestMapping("/insertStudent")
    public ModelAndView insertStudent(int sId,String sName){
        ModelAndView m = new ModelAndView("delect");
        if (studentService.selectStudent(sId) != null){
            m.addObject("message", "学号" + sId + "存在"+"注册失败");
        }else{
            boolean b = studentService.insertStudent(sId,sName);
            if (b) {
                m.addObject("message", "注册" + sId + "成功");
            } else
                m.addObject("message", "注册" + sId + "失败");
        }

        return m;
    }
}

